package com.example.esp8266.activity.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.esp8266.R;
import com.example.esp8266.activity.MainActivity;
import com.example.esp8266.activity.utile.SpannableUtil;
import com.example.esp8266.activity.utile.MouthpieceTool;
import com.example.esp8266.activity.utile.SocketLink;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
 * @Author lgd
 * @Date 2023/3/21 10:56
 */
public class LogPrintFragment extends Fragment implements View.OnClickListener{
    View view;
    private SocketLink socketLink;
    MainActivity mainActivity;
    private MouthpieceTool mouthpieceTool;
    Button logPrintBt;
    TextView logPrintTv;
    EditText logScanEt;
    ImageView scanIv;
    private String etStr;
    private StringBuilder stringBuilder;
    private int logPrintState;
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_log_print,container,false);
        init();
        mainActivity = (MainActivity) getActivity();
        if (mainActivity != null){
            socketLink = mainActivity.getSocketLink();
            mouthpieceTool = mainActivity.getMouthpieceTool();
        }
        if (!EventBus.getDefault().isRegistered(this)) { //判断是否注册，避免重复注册
            EventBus.getDefault().register(this);
        }
        setHintKeyboardView(view);  //关闭软键盘
        stringBuilder = new StringBuilder();
        logPrintState =1;
        return view;
    }

    public void init(){
        logPrintBt = view.findViewById(R.id.logPrint_bt);
        logPrintBt.setOnClickListener(this);
        logPrintTv = view.findViewById(R.id.logPrint_tv);
        logScanEt = view.findViewById(R.id.logScan_et);
        scanIv = view.findViewById(R.id.scan_iv);
        scanIv.setOnClickListener(this);
    }
    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.logPrint_bt:  // 打印日志 按钮
                if (logPrintState == 1){
                    String sendLogStr = "logPrint";
                    socketLink.sendString(sendLogStr);
                    logPrintState = 0;
                }
                break;
            case R.id.scan_iv: // 搜索关键字
                String string = String.valueOf(stringBuilder);
                string = string.replace("\\n","\n");
                etStr = logScanEt.getText().toString().trim();
                if (!etStr.equals("")){
                    logPrintTv.setText(SpannableUtil.findSearch(Color.RED,string,etStr)); //单个关键字
                }else {
                    // 多个关键字 高亮操作
                    List<String> list = new ArrayList<>();
                    list.add("time");
                    list.add("count");
                    list.add("volume");
                    String[] strings = list.toArray(new String[0]);
                    SpannableUtil.findSearch(Color.RED,string, String.valueOf(list)); //多个关键字方法
                    logPrintTv.setText(SpannableUtil.findSearch(Color.RED,string, strings));
                }
                break;
            default:
                break;
        }
    }
    //接收wifi回传指令
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(String str){
        System.out.println("----------日志打印--------------  "+str);
        String stringResult = null;
            if (str.substring(0,8).equals("6C6F673A")){
                String log = str.substring(8);
                System.out.println("----日志-------"+log+"------------");
                stringResult = asciiToString(log);
                stringBuilder.append(stringResult);
                logPrintTv.setText(stringBuilder);
//                popWindowSuccess("日志打印成功").show();
            }
    }
    //成功提示弹窗
    public Toast popWindowSuccess(final String content) {
        Toast toast =  Toast.makeText(getContext(), content,
                Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.CENTER, 0, 0);
        return toast;
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
    @Override
    public void onStop() {
        EventBus.getDefault().unregister(this);
        super.onStop();
    }

    /**
     * 设置点击软键盘之外区域，软键盘消失
     *
     * @param view
     */
    public void setHintKeyboardView(View view) {
        if (!(view instanceof EditText)) {
            view.setOnTouchListener(new View.OnTouchListener() {
                public boolean onTouch(View v, MotionEvent event) {
                    hintKeyboard(getActivity());
                    return false;
                }
            });
        }
        if (view instanceof ViewGroup) {
            for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
                View innerView = ((ViewGroup) view).getChildAt(i);
                setHintKeyboardView(innerView);
            }
        }
    }
    public  void hintKeyboard(Activity activity) {
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm.isActive() && activity.getCurrentFocus() != null) {
            if (activity.getCurrentFocus().getWindowToken() != null) {
                imm.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }
    // 将16进制 ASCII转成字符串
    public static String asciiToString(String str) {
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < str.length(); i += 2) {
            stringBuilder.append((char) Integer.parseInt(str.substring(i, i + 2), 16));
        }
        return stringBuilder.toString();
    }
}
